package filiter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;

@WebFilter({"/home","/home.jsp"})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器被初始化了");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器被执行了");
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        if (request.getSession().getAttribute("username")==null){
            request.setAttribute("msg","请登录后访问");
            request.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
        }
        filterChain.doFilter(servletRequest, servletResponse);  //放行
    }
    @Override

    public void destroy() {
        System.out.println("过滤器被销毁了");
    }
}